<template>
  <div class="app-container">
    <el-form :model="queryParams" ref="queryForm" size="small" :inline="true" v-show="showSearch" label-width="68px">
      <el-form-item label="患者姓名" prop="patientName">
        <el-input v-model="queryParams.patientName" placeholder="请输入患者姓名" clearable @keyup.enter.native="handleQuery" />
      </el-form-item>
      <!--      <el-form-item label="所属机构" prop="deptId">
              <el-input v-model="queryParams.deptId" placeholder="请输入所属机构ID" clearable  @keyup.enter.native="handleQuery"/>
            </el-form-item>-->
      <el-form-item label="手机号" prop="tel">
        <el-input v-model="queryParams.tel" placeholder="请输入手机号" clearable @keyup.enter.native="handleQuery" />
      </el-form-item>
      <el-form-item label="血片编号" prop="sliceNo">
        <el-input v-model="queryParams.sliceNo" placeholder="请输入血片编号" clearable @keyup.enter.native="handleQuery" />
      </el-form-item>
      <!--      <el-form-item label="预约项目" prop="gender">
              <el-select v-model="queryParams.subscreening" placeholder="请选择筛查项目" clearable>
                <el-option
                  v-for="dict in this.screeningOptions"
                  :key="dict.value"
                  :label="dict.label"
                  :value="dict.value"
                />
              </el-select>
            </el-form-item>-->
      <!--      <el-form-item label="筛查结果" prop="status">
              <el-select v-model="queryParams.status" placeholder="请选择筛查结果" clearable>
                <el-option
                  v-for="dict in dict.type.his_screening_status"
                  :key="dict.value"
                  :label="dict.label"
                  :value="dict.value"
                />
              </el-select>
            </el-form-item>-->
      <el-form-item>
        <el-button type="primary" icon="el-icon-search" size="mini" @click="handleQuery">搜索</el-button>
        <el-button icon="el-icon-refresh" size="mini" @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>

    <el-row :gutter="10" class="mb8">
      <!--<el-col :span="1.5">
        <el-button type="primary"  plain icon="el-icon-plus" size="mini" @click="handleAdd" v-hasPermi="['his:patient:add']" >新增</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button type="success" plain icon="el-icon-edit" size="mini" :disabled="multiple" @click="handleProcess" v-hasPermi="['his:patient:process']">审核</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button type="info" plain icon="el-icon-upload2" size="mini" @click="handleImport" v-hasPermi="['his:attribute:batch']">批量上传结果</el-button>
      </el-col>-->
    </el-row>

    <el-table v-loading="loading" :data="patientList" @selection-change="handleSelectionChange">
      <el-table-column type="selection" width="55" align="center" />
      <el-table-column label="序号" align="center" prop="id" width="50px"/>
      <el-table-column label="姓名" align="center" :show-overflow-tooltip="true">
        <template slot-scope="scope">
          <router-link :to="'/his/reg_treat/lnpg_edit/' + scope.row.id" class="link-type">
            <span>{{ scope.row.patientName }}</span>
          </router-link>
        </template>
        <router-view :key="$route.fullPath" />
      </el-table-column>
      <el-table-column label="性别" align="center" prop="gender" width="50px">
        <template slot-scope="scope">
          <dict-tag :options="dict.type.his_doctor_sex" :value="scope.row.gender" />
        </template>
      </el-table-column>
      <el-table-column label="ID号血片编号" align="center" prop="sliceNo" width="119px"/>
      <el-table-column label="电话" align="center" prop="tel"/>
      <el-table-column label="筛查项目" align="center" prop="subscreening" width="239px"/>
      <el-table-column label="门诊号" align="center" prop="outpatient" width="132px">
        <template slot-scope="scope">
          <div v-if="scope.row.outpatient!=null">{{scope.row.outpatient}}</div>
          <div v-else>--</div>
        </template>
      </el-table-column>
      <el-table-column label="年龄" align="center" prop="age" width="50px"/>
      <el-table-column label="体重" align="center" prop="weight" />

      <el-table-column label="筛查结果" align="center" prop="status" >
        <template slot-scope="scope">
          <dict-tag :options="dict.type.his_screening_status" :value="scope.row.status" v-on:click.native="handleCommand(scope.row)" style="cursor: pointer"/>
        </template>
      </el-table-column>
      <el-table-column label="录入时间" align="center" prop="createTime" width="129px">
        <template slot-scope="scope">
          <span>{{ parseTime(scope.row.createTime, '{y}-{m}-{d}') }}</span>
        </template>
      </el-table-column>
      <el-table-column label="操作" align="center" class-name="small-padding fixed-width"width="129px" >
        <template slot-scope="scope">
          <!--          <el-button
                      size="mini"
                      type="text"
                      icon="el-icon-edit"
                      @click="handleUpdate(scope.row)"
                      v-hasPermi="['his:patient:edit']"
                    >修改</el-button>-->
          <!--          <el-button type="primary" size="mini" @click="handleUpdate(scope.row)" v-hasPermi="['his:patient:edit']">编辑</el-button>-->
          <router-link :to="'/his/reg_treat/lnpg_edit/' + scope.row.id">
            <el-button type="text" icon="el-icon-edit">编辑</el-button>
          </router-link>
<!--          <router-link :to="'/his/reg_treat/patient_edit/' + scope.row.id" style="margin-left: 5px">
            <el-button type="text" icon="el-icon-view">查看</el-button>
          </router-link>-->
          <!--          <el-button
                      size="mini"
                      type="text"
                      icon="el-icon-delete"
                      @click="handleDelete(scope.row)"
                      v-hasPermi="['system:patient:remove']"
                    >删除</el-button>-->
        </template>
      </el-table-column>

    </el-table>

    <pagination v-show="total > 0" :total="total" :page.sync="queryParams.pageNum" :limit.sync="queryParams.pageSize"
                @pagination="getList" />

    <!-- 添加或修改患者对话框 -->
    <el-dialog :title="title" :visible.sync="open" width="560px" append-to-body>
      <el-form ref="form" :model="form" :rules="rules" label-width="96px">
        <el-form-item label="患者姓名" prop="patientName">
          <el-input v-model="form.patientName" placeholder="请输入患者姓名" />
        </el-form-item>
        <el-form-item label="性别" prop="gender">
          <el-select v-model="form.gender" placeholder="请选择性别" clearable>
            <el-option
              v-for="dict in dict.type.his_doctor_sex"
              :key="dict.value"
              :label="dict.label"
              :value="dict.value"
            />
          </el-select>
        </el-form-item>
        <el-form-item label="筛查类型" prop="type">
          <el-select v-model="form.type" placeholder="请选择筛查结果" clearable>
            <el-option
              v-for="dict in dict.type.his_type"
              :key="dict.value"
              :label="dict.label"
              :value="dict.value"
            />
          </el-select>
        </el-form-item>
        <el-form-item label="筛查结果" prop="riskWarning">
          <el-select v-model="form.riskWarning" placeholder="请选择筛查结果" clearable>
            <el-option
              v-for="dict in riskWarning"
              :key="dict.value"
              :label="dict.label"
              :value="dict.value"
            />
          </el-select>
        </el-form-item>
        <el-form-item label="所属机构" prop="unit">
          <el-input v-model="form.unit" placeholder="请输入所属机构ID" disabled/>
        </el-form-item>
        <el-form-item label="电话号码" prop="tel">
          <el-input v-model="form.tel" placeholder="请输入患者电话" />
        </el-form-item>
        <el-form-item label="血片编号" prop="sliceNo">
          <el-input v-model="form.sliceNo" placeholder="请输入血片编号" />
        </el-form-item>
        <el-form-item label="身份证号" prop="idCard">
          <el-input v-model="form.idCard" placeholder="请输入身份证号" />
        </el-form-item>
        <el-form-item label="患者年龄" prop="age">
          <el-input v-model="form.age" placeholder="请输入患者年龄" />
        </el-form-item>

        <el-form-item label="地址信息" prop="address">
          <el-input v-model="form.address" placeholder="请输入地址信息" />
        </el-form-item>
        <!--        <el-form-item label="出生日期" prop="patientDate">
                  <el-date-picker clearable
                                  v-model="form.patientDate"
                                  type="date"
                                  value-format="yyyy-MM-dd"
                                  placeholder="请选择出生日期">
                  </el-date-picker>
                </el-form-item>-->
        <!--        <el-form-item label="过敏史" prop="allergy">
                  <el-input v-model="form.allergy" type="textarea" placeholder="请输入内容" />
                </el-form-item>-->
        <!--        <el-form-item label="删除标志" prop="delFlag">
                  <el-input v-model="form.delFlag" placeholder="请输入删除标志" />
                </el-form-item>-->
        <el-form-item label="备注" prop="remark">
          <el-input v-model="form.remark" placeholder="请输入备注" />
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitForm">确 定</el-button>
        <el-button @click="cancel">取 消</el-button>
      </div>
    </el-dialog>

    <!-- 审核对话框 -->
    <el-dialog :title="title" :visible.sync="process" width="390px" append-to-body>
      <el-form ref="formProcess" :model="formProcess" :rules="rulesProcess" label-width="96px">
        <el-form-item label="审核状态" prop="status">
          <el-select v-model="formProcess.status" placeholder="请选择审核状态" clearable>
            <el-option
              v-for="dict in dict.type.his_screening_status"
              :key="dict.value"
              :label="dict.label"
              :value="dict.value"
            />
          </el-select>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitProcess">确 定</el-button>
        <el-button @click="cancel">取 消</el-button>
      </div>
    </el-dialog>


    <!-- 导入对话框 -->
    <el-dialog :title="upload.title" :visible.sync="upload.open" width="400px" append-to-body>
      <el-upload
        ref="upload"
        :limit="1"
        accept=".xlsx, .xls"
        :headers="upload.headers"
        :action="upload.url + '?updateSupport=' + upload.updateSupport + '&patientId=' + upload.patientId"
        :disabled="upload.isUploading"
        :on-progress="handleFileUploadProgress"
        :on-success="handleFileSuccess"
        :auto-upload="false"
        drag
      >
        <i class="el-icon-upload"></i>
        <div class="el-upload__text">将文件拖到此处，或<em>点击上传</em></div>
        <div class="el-upload__tip text-center" slot="tip">
          <div class="el-upload__tip" slot="tip">
            <el-checkbox v-model="upload.updateSupport" /> 是否更新已经存在的用户数据
            <el-input v-model="upload.patientId" type="hidden" ></el-input>
          </div>
          <span>仅允许导入xls、xlsx格式文件。</span>
          <el-link type="primary" :underline="false" style="font-size:12px;vertical-align: baseline;" @click="importTemplate">下载模板</el-link>
        </div>
      </el-upload>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitFileForm">确 定</el-button>
        <el-button @click="upload.open = false">取 消</el-button>
      </div>
    </el-dialog>
  </div>

</template>

<script>
import { listPatient, addPatient, updatePatient, updateProcess, listPatientLnpg } from '@/api/his/patient'
import { getToken } from '@/utils/auth'
import { delBpn, getBpn } from '@/api/his/bpn'
import { getUserProfile } from '@/api/system/user'
import { addScreening } from '@/api/his/screening'

export default {
  watch: {
    '$route': function () {
      this.getList()
    }
  },
  dicts: ['his_doctor_sex','his_screening_status','his_type'],
  name: "lnpg",
  data() {
    return {
      // 遮罩层
      loading: true,
      // 选中数组
      ids: [],
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      // 显示搜索条件
      showSearch: true,
      // 总条数
      total: 0,
      // 患者表格数据
      patientList: [],
      // 弹出层标题
      title: "",
      // 是否显示弹出层
      open: false,
      process: false,
      // 查询参数
      queryParams: {
        paramType:'',
        delFlag: 0,
        //screeningType:'老年综合评估',
        screeningItem:'老年综合评估',
        subscreening:'老年综合评估',
        pageNum: 1,
        pageSize: 10,
        patientName: null,
        tel: null,
        idCard: null,
        sliceNo: null,
        age: null,
        gender: null,
        address: null,
        patientDate: null,
        createTime: null
      },
      screeningOptions:[
        {lable:'实验室老年衰弱/肌少症',value:'实验室老年衰弱/肌少症'},
        {lable:'快速综合评估',value:'快速综合评估'},
      ],
      riskWarning:[
        {label:'正常',value:'正常'},
        /* {label:'老年综合症',value:'老年综合症'}, */
        {label:'衰弱',value:'衰弱'},
        {label:'重度衰弱',value:'重度衰弱'},
      ],
      // 表单参数
      form: {
        riskWarning:''
      },
      formResult:{
        riskWarning:''
      },
      formProcess:{
        ids:[],
        status:""
      },
      // 表单校验
      rules: {
        patientName: [
          { required: true, message: "姓名不能为空", trigger: "blur" }
        ],
        tel: [
          { required: true, message: "请输入正确的手机号码", trigger: "blur",pattern: /^1[3|4|5|6|7|8|9][0-9]\d{8}$/ }
        ],
        idCard: [
          { required: true, message: "请输入正确的身份证号码", trigger: "blur",pattern: /(^\d{15}$)|(^\d{18}$)|(^\d{17}(\d|X|x)$)/ }
        ],
        sliceNo: [
          { required: true, message: "血片编号不能为空", trigger: "blur" }
        ],
        type: [
          { required: true, message: "请选择筛查类型", trigger: "change" }
        ],
        gender: [
          { required: true, message: "请选择性别", trigger: "change" }
        ],
      },
      rulesProcess:{
        status: [
          { required: true, message: "请选择审核状态", trigger: "change" }
        ],
      },

      // 导入指标参数
      upload: {
        patientId: 0,
        // 是否显示弹出层（数据导入）
        open: false,
        // 弹出层标题（数据导入）
        title: "",
        // 是否禁用上传
        isUploading: false,
        // 是否更新已经存在的用户数据
        updateSupport: 0,
        // 设置上传的请求头部
        headers: { Authorization: "Bearer " + getToken() },
        // 上传的地址
        //url: process.env.VUE_APP_BASE_API + "/his/attribute/importData"
        url: process.env.VUE_APP_BASE_API + "/his/attribute/batchImportData"
      }
    };
  },
  created() {
    this.queryParams.paramType = this.$route.path;
    this.getList();
  },
  methods: {
    handleCommand(row){
      this.$router.push("/his/reg_treat/lnpg_edit/" + row.id);
    },
    /** 查询患者列表 */
    getList() {
      //console.log('this.queryParams: ',this.queryParams)
      this.loading = true;
      listPatientLnpg(this.queryParams).then(response => {
        //console.log('response=>',response)
        this.patientList = response.rows;
        this.total = response.total;
        this.loading = false;
      });
    },
    // 取消按钮
    cancel() {
      this.open = this.process = false;
      this.reset();
    },
    // 表单重置
    reset() {
      this.form = {
        patientId: null,
        patientName: null,
        tel: null,
        idCard: null,
        age: null,
        gender: "0",
        address: null,
        patientDate: null,
        delFlag: null,
        createBy: null,
        createTime: null,
        updateBy: null,
        updateTime: null,
        remark: null,
        unit: null
      };
      this.resetForm("form");
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.pageNum = 1;
      this.getList();
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.resetForm("queryForm");
      this.handleQuery();
    },
    /** 新增按钮操作 */
    handleAdd() {
      this.reset();
      this.getUser();
      this.open = true;
      this.title = "添加患者";
    },
    /** 修改按钮操作 */
    handleUpdate(row) {
      //alert(row.patientId)
      this.$router.push({ path: '/his/reg_treat/patient_edit', query: { id: row.patientId }})

      /* const patientId = row.patientId || this.ids
      getPatient(patientId).then(response => {
        this.form = response.data;
        this.open = true;
        this.title = "修改患者";
      }); */
    },

    /** 审核按钮操作 */
    handleProcess(row) {
      //this.reset();
      const id = row.id || this.ids
      this.process = true;
      this.title = "用户审核";
      this.formProcess.ids = id;
    },
    submitProcess() {
      this.$refs["formProcess"].validate(valid => {
        if (valid) {
          const ids = [];//this.formProcess.ids;
          this.formProcess.ids.forEach((self)=>{
            ids.push(self+'-'+this.formProcess.status)
          })
          this.$modal.confirm('是否确认审核ID为"' + this.formProcess.ids + '"的数据项？').then(() => {
            return updateProcess(ids);
          }).then(()=>{
            this.getList();
            this.$modal.msgSuccess("操作成功");
            this.process = false;
          }).catch(() => {
            this.process = false;
          });
        }
      })
    },

    // 多选框选中数据
    handleSelectionChange(selection) {
      this.ids = selection.map(item => item.id)
      this.single = selection.length !== 1
      this.multiple = !selection.length
    },

    /** 提交按钮 */
    submitForm() {
      this.$refs["form"].validate(valid => {
        if (valid) {
          if (this.form.patientId != null) {
            updatePatient(this.form).then(response => {
              this.$modal.msgSuccess("修改成功");
              this.open = false;
              this.getList();
            });
          } else {
            this.form.screeningType  = '老年综合评估';
            this.form.subscreening  = '老年综合评估';
            this.formResult.subscreening = this.formResult.screeningItem = '老年综合评估';
            this.formResult.riskWarning = this.form.riskWarning;
            addPatient(this.form).then(response => {
              this.formResult.patientId = response.data
              this.formResult.addTime = Date.now();
              addScreening(this.formResult).then(response => {
                this.$modal.msgSuccess("新增成功");
                this.open = false;
                this.getList();
              });
            });
          }
        }
      });
    },

    /** 删除按钮操作 */
    handleDelete(row) {
      const ids = row.id || this.ids;
      this.$modal.confirm('是否确认删除编号为"' + ids + '"的数据项？').then(function() {
        return delPatient(patientIds);
      }).then(() => {
        this.getList();
        this.$modal.msgSuccess("删除成功");
      }).catch(() => {});
    },

    handleCancel: function() {
      this.$router.push({ path: '/patient'})
    },

    /** 导入按钮操作 */
    handleImport() {
      this.upload.title = "筛查结果导入";
      this.upload.open = true;
    },
    /** 下载模板操作 */
    importTemplate() {
      this.download('his/attribute/importTemplate', {
      }, `attribute_template_${new Date().getTime()}.xlsx`)
    },
    // 文件上传中处理
    handleFileUploadProgress(event, file, fileList) {
      this.upload.isUploading = true;
    },
    // 文件上传成功处理
    handleFileSuccess(response, file, fileList) {
      this.upload.open = false;
      this.upload.isUploading = false;
      this.$refs.upload.clearFiles();
      this.$alert(response.msg, "导入结果", { dangerouslyUseHTMLString: true });
      this.getList();
    },
    // 提交上传文件
    submitFileForm() {
      this.$refs.upload.submit();
    },

    /** 导出按钮操作 */
    handleExport() {
      this.download('his/patient/export', {
        ...this.queryParams
      }, `patient_${new Date().getTime()}.xlsx`)
    },

    getUser() {
      getUserProfile().then(response => {
        //console.log('response.data:',response.data)
        this.form.unit = response.data.dept.deptName;
        this.form.deptId = response.data.dept.deptId;
      });
    }
  }
};
</script>
